package com.course.app.biz;

import com.course.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * Created by Justin on 2017/5/30.
 */
@Component
public class AuthBiz {

    private final AuthenticationManager manager;

    @Autowired
    public AuthBiz(AuthenticationManager authManager) {
        this.manager = authManager;
    }

    public String login(String username, String password) {
        try {
            Authentication token = manager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
            SecurityContextHolder.getContext().setAuthentication(token);
            return AuthUtils.toToken(username);
        } catch (AuthenticationException e) {
            return null;
        }
    }
}
